package com.cloudspace.yunloan.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cloudspace.yunloan.R;
import com.cloudspace.yunloan.YunloanApp;
import com.cloudspace.yunloan.constants.Constants;
import com.cloudspace.yunloan.log.APPLog;
import com.cloudspace.yunloan.titlestyle.ToolBarHelper;
import com.cloudspace.yunloan.utils.AppPreferences;
import com.cloudspace.yunloan.utils.Device;
import com.cloudspace.yunloan.window.StatusBarUtils;

public class YunloanBaseActivity extends AppCompatActivity {
    public final static String TAG = YunloanBaseActivity.class.getSimpleName();
    private static final int LOCATION_REQUEST_CODE = 501;

    private ToolBarHelper mToolBarHelper;
    public Toolbar toolbar;

    protected static long activityCnt = 0;

    protected boolean isToolBarVisible = true;      //是否显示自定义toolbar

    private LocationClient mLocClient;
    private BDLocationListener myListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            String addr = bdLocation.getAddrStr();
            Log.d(TAG, addr);
            AppPreferences.putString(Constants.ADDRESS, addr);
        }
    };


    @Override
    public void setContentView(int layoutResID) {
        mToolBarHelper = new ToolBarHelper(this, layoutResID, isToolBarVisible);
        toolbar = mToolBarHelper.getToolBar();
        setContentView(mToolBarHelper.getContentView());
        setSupportActionBar(toolbar);
        onCreateCustomToolBar(toolbar);

        setToolbarVisible(isToolBarVisible);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.zhutilan);


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_REQUEST_CODE);
        }else{
            startLocation();
        }

        if (YunloanApp.getInstance().getScreenWidth() == 0){
            YunloanApp.getInstance().initScreenParams(getWindowManager().getDefaultDisplay());
        }
    }

    private void startLocation() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setScanSpan(1000);
        option.setAddrType("all");
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    private void setToolbarVisible(boolean isToolBarVisible) {
        if (isToolBarVisible) {
            return;
        }

        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            toolbar.setTranslationY(-actionBarHeight);
        }
    }

    public void onCreateCustomToolBar(Toolbar toolbar) {
        toolbar.setContentInsetsRelative(0, 0);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((YunloanApp)getApplication()).addActivity(this);

    }

    @Override
    protected void onDestroy() {
        ((YunloanApp)getApplication()).removeActivity(this);
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
        ++activityCnt;
    }

    public long getActiveActivityCnt(){
        return activityCnt;
    }


    @Override
    protected void onStop() {
        super.onStop();

        --activityCnt;
    }


    /**
     * @return true:foreground
     */
    public static boolean isForeground() {
        return activityCnt > 0;
    }


    @TargetApi(Build.VERSION_CODES.M)
    public boolean hasPermission(String permission) {
        if (Device.isPreM()) return true;
        return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    @TargetApi(Build.VERSION_CODES.M)
    public void requestPermission(String permission, int requestCode) {
        if (shouldShowRequestPermissionRationale(permission)) {
            //TODO explain permission
        }
        requestPermissions(new String[]{permission}, requestCode);
    }

    public boolean checkPermission(String permission, int requestCode) {
        if (!hasPermission(permission)) {
            requestPermission(permission, requestCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case LOCATION_REQUEST_CODE:
                startLocation();
            break;
        }
    }
}
